package com.woniu.ly.manageassembly.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.ly.facade.ManageFeignClient;
import com.woniu.ly.manageassembly.common.OssUtil;
import com.woniu.ly.manageassembly.component.AdminSeckillComponent;
import com.woniu.ly.manageassembly.component.CallBack;
import com.woniu.ly.manageassembly.config.RabbitConfig;
import com.woniu.ly.manageassembly.model.info.Operation;
import com.woniu.ly.manageassembly.model.info.Singleton;
import com.woniu.ly.manageassembly.service.AdminService;
import com.woniu.ly.model.common.Result;
import com.woniu.ly.model.model.*;


import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@Slf4j
public class AdminController implements ManageFeignClient {
    @Autowired
    private AdminService adminService;
    /*
    * 新增导游
    * */
    public Result addGuide(String guideName){
        log.info("新增导游名为：{}",guideName);
        Guide guide = new Guide();
        guide.setGuideName(guideName);
        guide.setGuideNum(0);
        guide.setGuideStatus("空闲");
        guide.setGuideComplain(0);
        int i = adminService.addGuide(guide);
        log.info("id:{}",i);
        // 数据持久化
        return Result.success("新增成功");
    }
    /*
     * 录入散客信息(证件号码、持证人姓名、有效期、证件类型、出行人电话、订单id)
     * */
    public Result addScatteredPassengers(
            String cardNum, String cardHolder, Timestamp cardIndate, String cardType
            , String travelerTel
            , int orderId, int tourId, int cooperatorId, double cooperatorRatio){
        // 录入证件信息
        Card card = new Card();
        card.setCardNum(cardNum);
        card.setCardHolder(cardHolder);
        card.setCardIndate(cardIndate);
        card.setCardType(cardType);

        int cardId = adminService.addCard(card);
        log.info("证件内容为：{}",card);
        // 录入出行人
        Traveler traveler = new Traveler();
        traveler.setTourId(tourId);
        traveler.setTravelerType("散客");
        traveler.setUserId(0);// 散客为后台录入。默认关联为0
        traveler.setTravelerTel(travelerTel);
        traveler.setCardId(cardId);
        int travelerId = adminService.addTraveler(traveler);
        log.info("出行人内容为：{}",traveler);
        //录入散客信息为
        Singleton singleton = new Singleton();
        singleton.setTravelerId(travelerId);
        singleton.setOrderId(orderId);
        singleton.setTourId(tourId);
        singleton.setCooperatorId(cooperatorId);
        singleton.setCooperatorRatio(cooperatorRatio);
        log.info("录入散客信息为：{}",singleton);
        adminService.addScatteredPassengers(singleton);
        return Result.success("添加完成");
    }
    /*
     * 结束旅行团
     * */
    public Result finishTour(int guideId,int tourId){
        log.info("导游id：{},结束旅行id为：{}",guideId,tourId);
        // 修改旅行团状态
        adminService.changeTourStatus(tourId,"结束旅行团");
        // 修改导游状态
//        adminService.changeGuideStatus(guideId,"空闲");
        // 增加导游带团次数,修改导游状态
        Guide guide = adminService.selectGuideById(guideId);
        guide.setGuideStatus("空闲");
        guide.setGuideNum(guide.getGuideNum()+1);
        adminService.updateGuideNumb(guide);
        return Result.success("结束成功");
    }
    /*
     * 结束秒杀旅行团
     * */
    public Result finishSeckillTour(int guideId,int seckillTourId){
        log.info("导游id：{},结束旅行id为：{}",guideId,seckillTourId);
        // 修改旅行团状态
        adminService.changeSeckillTourStatus(seckillTourId,"结束旅行团");
        // 修改导游状态
//        adminService.changeGuideStatus(guideId,"空闲");
        Guide guide = adminService.selectGuideById(guideId);
        guide.setGuideStatus("空闲");
        guide.setGuideNum(guide.getGuideNum()+1);
        adminService.updateGuideNumb(guide);
        return Result.success("结束成功");
    }

    @Override
    public Result getUserOrderDetailStatus(@RequestParam(defaultValue = "1") int curr,@RequestParam(defaultValue = "5") int size, String userOrderDetailStatus) {
        Page<UserOrderDetail> page = new Page<>();
        page.setSize(size);
        page.setCurrent(curr);
        IPage<UserOrderDetail> iPage = adminService.getUserOrderDetailStatus(page,userOrderDetailStatus);
        return Result.success(iPage);
    }

    /*
     * 秒杀团选择导游
     * */
    public Result chooseSeckillGuide(int guideId,int seckilltourId){
        log.info("导游id：{},旅行团id为：{}",guideId,seckilltourId);
        // 给团安排导游
        adminService.chooseSeckillGuide(guideId, seckilltourId);
        // 修改导游状态
        adminService.changeGuideStatus(guideId,"跟团中");
        return Result.success("选择成功");
    }
    /*
     * 选择导游
     * */
    public Result chooseGuide(int guideId,int tourId){
        log.info("导游id：{},旅行团id为：{}",guideId,tourId);
        // 给团安排导游
        adminService.chooseGuide(guideId, tourId);
        // 修改导游状态
        adminService.changeGuideStatus(guideId,"跟团中");
        return Result.success("选择成功");
    }
    /*
     * 查看所有导游信息
     * */
    public Result getGuide(String guideStatus, String guideName
            , @RequestParam(defaultValue = "1") int currPage
            , @RequestParam(defaultValue = "5") int size){
        log.info("导游状态：{}，导游姓名：{}，当前页：{}，每页条数：{}",guideStatus,guideName,currPage,size);
        // 动态sql查询
        Page<Guide> page = new Page<>();
        page.setSize(size);
        page.setCurrent(currPage);
        IPage<Guide> complainuserIpage = adminService.getGuide(page, guideStatus, guideName);
        return Result.success(complainuserIpage);
    }
    /*
     * 新增酒店（图片后续添加，营业时间）
     * */
    public Result addAdminHotel(String hotelName
            , String hotelTel
            , String hotelAddress
            , double hotelLongitude
            , double hotelLatitude
            , MultipartFile hotelImgFile) throws IOException {
        Hotel hotel = new Hotel();
        hotel.setHotelName(hotelName);
        hotel.setHotelTel(hotelTel);
        hotel.setHotelAddress(hotelAddress);
        hotel.setHotelLongitude(hotelLongitude);
        hotel.setHotelLatitude(hotelLatitude);
        hotel.setHotelStatus("营业中");
        hotel.setHotelComplain(0);
        log.info("酒店信息为：{}",hotel);
        int hotelId = adminService.addHotel(hotel);
        log.info("酒店id为：{}",hotelId);
        // 新增酒店图片
        String originalFilename = hotelImgFile.getOriginalFilename();
        String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filename = UUID.randomUUID() + fileType;
        hotelImgFile.transferTo(new File("D:\\java\\temp" + filename));
        // 上传到OSS服务器
        OssUtil ossUtil = new OssUtil();
        String filePath = ossUtil.upFiles(filename, "D:\\java\\temp" + filename);
        HotelImg hotelImg = new HotelImg();
        hotelImg.setHotelId(hotelId);
        hotelImg.setHotelImgUrl(filePath);
        adminService.addHotelImg(hotelImg);
        return Result.success("新增成功");
    }
    /*
     * 审核（给与记录）
     * @Param operationContent (驳回/通过)
     * */
    public Result hotelAdminAudit(int hotelId,String operationContent,String operationReason){
        Operation operation = new Operation();
        operation.setOperationReason(operationReason);
        operation.setOperationType("酒店");
        operation.setOperationType_id(hotelId);
        operation.setOperationContent(operationContent);
        operation.setOperationTime(Timestamp.valueOf(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
        log.info("操作记录：{}",operation);
        // 修改酒店状态
        if (operationContent.equals("驳回")){
            adminService.changeHotelStatus(hotelId, "未营业");
        }else{
            // 通过
            adminService.changeHotelStatus(hotelId, "营业中");
        }
        // 记录进入操作记录表
        adminService.addOperation(operation);
        return Result.success("审核操作完成");
    }
    /*
     * 下架酒店（给与记录）
     * */
    public Result hotelAdminOff(int hotelId,String operationReason){
        Operation operation = new Operation();
        operation.setOperationReason(operationReason);
        operation.setOperationType("酒店");
        operation.setOperationType_id(hotelId);
        operation.setOperationContent("下架");
        operation.setOperationTime(Timestamp.valueOf(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
        log.info("操作记录：{}",operation);
        adminService.changeHotelStatus(hotelId, "未营业");
        // 记录进入操作记录表
        adminService.addOperation(operation);
        return Result.success("酒店下架完成");
    }

    public Result addSpot(String spotName,double spotPrice,String spotContent,
                            double spotLongitude,double spotLatitude,String spotAddress){
        Spot spot = new Spot();
        spot.setSpotName(spotName);
        spot.setSpotPrice(spotPrice);
        spot.setSpotContent(spotContent);
        spot.setSpotLongitude(spotLongitude);
        spot.setSpotLatitude(spotLatitude);
        spot.setSpotAddress(spotAddress);
        spot.setSpotStatus("open");
        adminService.addSpot(spot);
        return Result.success("添加成功");
    }

    public Result getAllspot(String spotName
            , @RequestParam(defaultValue = "1") int currPage
            , @RequestParam(defaultValue = "5") int size){
        Page<Spot> page = new Page<>();
        page.setSize(size);
        page.setCurrent(currPage);
        IPage<Spot> spots = adminService.getSpot(page, spotName);
        return Result.success(spots);
    }

    public Result getSpotById(int spotId){
        Spot spot = adminService.getSpotById(spotId);
        return Result.success(spot);
    }

    public Result modifySpotById(int spotId,double spotPrice,String spotContent){
        Spot spot = adminService.getSpotById(spotId);
        spot.setSpotPrice(spotPrice);
        spot.setSpotContent(spotContent);
        adminService.modifySpotById(spot);
        return Result.success("修改成功");
    }

    public Result closeSpotById(int spotId,String operationReason){
        Spot spot = adminService.getSpotById(spotId);
        spot.setSpotStatus("close");
        adminService.modifySpotById(spot);
        Operation operation = new Operation();
        operation.setOperationReason(operationReason);
        operation.setOperationType("景区");
        operation.setOperationType_id(spotId);
        operation.setOperationContent("下架");
        operation.setOperationTime(Timestamp.valueOf(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
        log.info("操作记录：{}",operation);
        // 记录进入操作记录表
        adminService.addOperation(operation);
        return Result.success("下架成功");
    }

    public Result addHotelImg(int hotelId,List<MultipartFile> hotelImgFiles){
        for (MultipartFile hotelImgFile : hotelImgFiles) {
            String originalFilename = hotelImgFile.getOriginalFilename();
            String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = UUID.randomUUID() + fileType;
            try {
                hotelImgFile.transferTo(new File("D:\\java\\temp" + filename));
                // 上传到OSS服务器
                OssUtil ossUtil = new OssUtil();
                String filePath = ossUtil.upFiles(filename, "D:\\java\\temp" + filename);
                HotelImg hotelImg = new HotelImg();
                hotelImg.setHotelId(hotelId);
                hotelImg.setHotelImgUrl(filePath);
                adminService.addHotelImg(hotelImg);
            }catch (IOException e){
                e.printStackTrace();
            }
            return Result.success("图片上传成功");
        }
        return Result.fail("图片上传失败");
    }

    public Result addSpotImg(int spotId,List<MultipartFile> spotImgFiles){
        for (MultipartFile spotImgFile : spotImgFiles) {
            String originalFilename = spotImgFile.getOriginalFilename();
            String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = UUID.randomUUID() + fileType;
            try {
                spotImgFile.transferTo(new File("D:\\java\\temp" + filename));
                // 上传到OSS服务器
                OssUtil ossUtil = new OssUtil();
                String filePath = ossUtil.upFiles(filename, "D:\\java\\temp" + filename);
                SpotImg spotImg = new SpotImg();
                spotImg.setSpotId(spotId);
                spotImg.setSpotImgUrl(filePath);
                adminService.addSpotImg(spotImg);
            }catch (IOException e){
                e.printStackTrace();
            }
            return Result.success("图片上传成功");
        }
        return Result.fail("图片上传失败");
    }
    /*
     * 上架酒店（给与记录）
     * */
    public Result hotelAdminOn(int hotelId,String operationReason){
        Operation operation = new Operation();
        operation.setOperationReason(operationReason);
        operation.setOperationType("酒店");
        operation.setOperationType_id(hotelId);
        operation.setOperationContent("上架");
        operation.setOperationTime(Timestamp.valueOf(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
        log.info("操作记录：{}",operation);
        adminService.changeHotelStatus(hotelId, "营业中");
        // 记录进入操作记录表
        adminService.addOperation(operation);
        return Result.success("酒店上架完成");
    }
    /*
    * 分页查询团信息（提供团id精确查找、团类型、产品id、团状态查询）
    * */
    public Result getTours(@RequestParam(defaultValue = "1") int curr
                           , @RequestParam(defaultValue = "5") int size
                           , int tourId
                           , String tourType
                           , int productId
                           , String tourStatus){
        Page<Tour> page = new Page<>();
        page.setSize(size);
        page.setCurrent(curr);
        IPage<Tour> iPage = adminService.getTours(page,tourId,tourType,productId,tourStatus);
        return Result.success(iPage);
    }
    /*
     * 秒杀分页查询团信息（提供团id精确查找、团类型、产品id、团状态查询）
     * */
    public Result getSeckillTours(@RequestParam(defaultValue = "1") int curr
            , @RequestParam(defaultValue = "5") int size
            , int seckilltourId
            , String tourType
            , int productId
            , String tourStatus){
        Page<Tour> page = new Page<>();
        page.setSize(size);
        page.setCurrent(curr);
        IPage<Tour> iPage = adminService.getSeckillTours(page,seckilltourId,tourType,productId,tourStatus);
        return Result.success(iPage);
    }

    /*
    * 制定旅游团（时间暂定传入String类型）
    * */
    public Result makeTourGroups(int productId
            , String tourType
            , double tourPrice
            , int tourMaxNum
            , String startTime){
        Timestamp ts = new Timestamp(System.currentTimeMillis());
        ts = Timestamp.valueOf(startTime);
        Tour tour = new Tour();
        tour.setProductId(productId);
        tour.setTourMaxNum(tourMaxNum);
        tour.setTourStartTime(ts);
        tour.setTourType(tourType);
        tour.setTourPrice(tourPrice);
        tour.setTourNowNum(0);
        tour.setTourStatus("等待开团");
        log.info("旅行团信息：{}",tour);
        int tourId = adminService.makeTourGroups(tour);
        log.info("旅行团Id：{}",tourId);
        return Result.success("制定旅行团成功");
    }
    /*
     * 制定秒杀游团（时间暂定传入String类型）
     * */
    public Result makeSeckillTourGroups(int productId
            , String tourType
            , double tourPrice
            , int tourMaxNum
            , String startTime
            , String seckillStartTime
            , String seckillEndTime){
//        Timestamp ts = new Timestamp(System.currentTimeMillis());
//        Timestamp ts = Timestamp.valueOf(startTime);
        SeckillTour tour = new SeckillTour();
        tour.setProductId(productId);
        tour.setTourMaxNum(tourMaxNum);
        tour.setTourStartTime(Timestamp.valueOf(startTime));
        tour.setSeckillStartTime(Timestamp.valueOf(seckillStartTime));
        tour.setSeckillEndTime(Timestamp.valueOf(seckillEndTime));
        tour.setTourType(tourType);
        tour.setTourPrice(tourPrice);
        tour.setTourNowNum(0);
        tour.setTourStatus("秒杀未开始");
        log.info("旅行团信息：{}",tour);
        int seckillTourId = adminService.makeSeckillTourGroups(tour);
        log.info("旅行团Id：{}",seckillTourId);
        return Result.success("制定旅行团成功");
    }
    /*
     * 确认开团（传入团id、操作[开团/取消团]），发送相应通知
     * 取消团，涉及退款
     * */
    public Result changeStatusTour(int tourId, String operation){
        log.info("团id为：{}，操作为：{}",tourId,operation);
        // 创建一个集合接收出行人信息
        List<Traveler> travelers = new ArrayList<>();
        Tour tour = adminService.getTour(tourId);
        if(tour.getTourStatus().equals("等待开团")){
            if (operation.equals("取消团")){
                adminService.changeTourStatus(tourId,"取消团");
                // 1、根据团id出该团相关的订单id
                List<UserOrder> userOrders = adminService.getUserOrders(tourId,"普通团");
                for(UserOrder uo:userOrders){
                    // 2、遍历获取订单id查询该订单出行人
                    List<UserOrderDetail> userOrderDetails = adminService.getUserOrderDetails(uo.getUserOrderId());
                    // 3、录入t_user_chargeback_detail用户退单详情表
                    for(UserOrderDetail uod:userOrderDetails){
                        UserChargebackDetail ucd = new UserChargebackDetail();
                        ucd.setTravelerId(uod.getTravelerId());
                        ucd.setUserChargebackdetailPrice(uod.getUserOrderDetailPrice());
                        ucd.setUserOrderId(uod.getUserOrderId());
                        ucd.setChargebackRemark("开团失败，无责退款");
                        log.info("用户退单详情信息为：{}",ucd);
                        int userChargebackDetailId = adminService.addUserChargebackDetail(ucd);
                        log.info("用户退单详情信息id：{}",userChargebackDetailId);
                        // 获取出行人id，查询出行人信息
                        Traveler traveler = adminService.getTraveler(ucd.getTravelerId());
                        travelers.add(traveler);
                    }
                    // 4、用户账户详情表
                    UserAccount userAccount = new UserAccount();
                    userAccount.setUserId(uo.getUserId());
                    userAccount.setUserAccountMoney(uo.getUserOrderPrice());
                    userAccount.setUserAccountType("退款");
                    userAccount.setUserAccountContent("开团失败，无责退款");
                    userAccount.setUserAccountTime(Timestamp.valueOf(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
                    int userAccountId = adminService.addUserAccount(userAccount);
                    // 5、平台账户详情表
                    PlatfromStatement platfromStatement = new PlatfromStatement();
                    platfromStatement.setStatementType("开团失败，无责退款");
                    platfromStatement.setOrderId(uo.getUserOrderId());
                    platfromStatement.setStatementAmount(uo.getUserOrderPrice());
                    platfromStatement.setOrderType("用户");
                    platfromStatement.setStatementTime(Timestamp.valueOf(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
                    int platfromStatementId = adminService.addPlatfromStatement(platfromStatement);
                    log.info("自增id为：{}",platfromStatementId);
                    // 6、修改平台账户金额
                    PlatfromAccount platfromAccount = new PlatfromAccount();
                    // 获取账户目前金额（最近的）
                    PlatfromAccount pt = adminService.getPlatfromAccount();
                    platfromAccount.setPlatfromAccountMoney(pt.getPlatfromAccountMoney()-uo.getUserOrderPrice());
                    platfromAccount.setStatementId(platfromStatementId);
                    adminService.addPlatfromAccount(platfromAccount);
                }
                // 将出行人信息集合发送到用户服务接收端
                rabbitTemplate.convertAndSend("refund.money.exchange",
                        "refund.money.key",
                        travelers,
                        new CorrelationData("退款信息已发送"));
                //添加一个确认的回调
                rabbitTemplate.setConfirmCallback(callBack);
                log.info("退款操作完成");
                return Result.success("取消团成功");
            }
            if(operation.equals("开团")){
                adminService.changeTourStatus(tourId,"开团");
                // 通知服务
                // 将出行人信息集合发送到用户服务接收端
                rabbitTemplate.convertAndSend("refund.money.exchange",
                        "refund.money.key",
                        travelers,
                        new CorrelationData("确认开团成功"));
                //添加一个确认的回调
                rabbitTemplate.setConfirmCallback(callBack);
                log.info("退款操作完成");
                return Result.success("确认开团成功");
            }
        }
        return Result.fail("操作不合法");
    }
    /*
     * 确认秒杀团（传入团id、操作[开团/取消团]），发送相应通知
     * 取消团，涉及退款
     * */
    public Result changeSeckillStatusTour(int SeckillTourId, String operation){
        log.info("团id为：{}，操作为：{}",SeckillTourId,operation);
        // 创建一个集合接收出行人信息
        List<Traveler> travelers = new ArrayList<>();
        // 查询旅行团状态（后端校验）
        SeckillTour tour = adminService.getSeckillTour(SeckillTourId);
        if(tour.getTourStatus().equals("等待开团")){
            if (operation.equals("取消团")){
                adminService.changeSeckillTourStatus(SeckillTourId,"取消团");
                // 退款服务
                // 1、根据团id出该团相关的订单id
                List<UserOrder> userOrders = adminService.getUserOrders(SeckillTourId,"普通团");
                for(UserOrder uo:userOrders){
                    // 2、遍历获取订单id查询该订单出行人
                    List<UserOrderDetail> userOrderDetails = adminService.getUserOrderDetails(uo.getUserOrderId());
                    // 3、录入t_user_chargeback_detail用户退单详情表
                    for(UserOrderDetail uod:userOrderDetails){
                        UserChargebackDetail ucd = new UserChargebackDetail();
                        ucd.setTravelerId(uod.getTravelerId());
                        ucd.setUserChargebackdetailPrice(uod.getUserOrderDetailPrice());
                        ucd.setUserOrderId(uod.getUserOrderId());
                        ucd.setChargebackRemark("开团失败，无责退款");
                        log.info("用户退单详情信息为：{}",ucd);
                        int userChargebackDetailId = adminService.addUserChargebackDetail(ucd);
                        log.info("用户退单详情信息id：{}",userChargebackDetailId);
                        // 获取出行人id，查询出行人信息
                        Traveler traveler = adminService.getTraveler(ucd.getTravelerId());
                        travelers.add(traveler);
                    }
                    // 4、用户账户详情表
                    UserAccount userAccount = new UserAccount();
                    userAccount.setUserId(uo.getUserId());
                    userAccount.setUserAccountMoney(uo.getUserOrderPrice());
                    userAccount.setUserAccountType("退款");
                    userAccount.setUserAccountContent("开团失败，无责退款");
                    userAccount.setUserAccountTime(Timestamp.valueOf(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
                    int userAccountId = adminService.addUserAccount(userAccount);
                    // 5、平台账户详情表
                    PlatfromStatement platfromStatement = new PlatfromStatement();
                    platfromStatement.setStatementType("开团失败，无责退款");
                    platfromStatement.setOrderId(uo.getUserOrderId());
                    platfromStatement.setStatementAmount(uo.getUserOrderPrice());
                    platfromStatement.setOrderType("用户");
                    platfromStatement.setStatementTime(Timestamp.valueOf(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
                    int platfromStatementId = adminService.addPlatfromStatement(platfromStatement);
                    log.info("自增id为：{}",platfromStatementId);
                    // 6、修改平台账户金额
                    PlatfromAccount platfromAccount = new PlatfromAccount();
                    // 获取账户目前金额（最近的）
                    PlatfromAccount pt = adminService.getPlatfromAccount();
                    platfromAccount.setPlatfromAccountMoney(pt.getPlatfromAccountMoney()-uo.getUserOrderPrice());
                    platfromAccount.setStatementId(platfromStatementId);
                    adminService.addPlatfromAccount(platfromAccount);
                }
                // 通知服务
                // 将出行人信息集合发送到用户服务接收端
                rabbitTemplate.convertAndSend("refund.money.exchange",
                        "refund.money.key",
                        travelers,
                        new CorrelationData("退款信息已发送"));
                //添加一个确认的回调
                rabbitTemplate.setConfirmCallback(callBack);
                log.info("退款操作完成");
                return Result.success("取消团成功");
            }
            if(operation.equals("开团")){
                adminService.changeSeckillTourStatus(SeckillTourId,"开团");
                // 通知服务
                // 将出行人信息集合发送到用户服务接收端
                rabbitTemplate.convertAndSend("refund.money.exchange",
                        "refund.money.key",
                        travelers,
                        new CorrelationData("确认开团成功"));
                //添加一个确认的回调
                rabbitTemplate.setConfirmCallback(callBack);
                log.info("退款操作完成");
                return Result.success("确认开团成功");
            }
        }
        return Result.fail("操作不合法");
    }
    /*
    * 团退款服务:传入团id（5张表：用户账户详情表，平台账户详情表，平台账户表，订单表，用户订单详情表，用户退单详情表）
    *  tourGenre判断团类型（普通团/秒杀团）
    * */
    public Result refundTour(int tourId, String tourGenre){
        log.info("团id为：{}，团类型：{}",tourId,tourGenre);
        // 创建一个集合接收出行人信息
        List<Traveler> travelers = new ArrayList<>();
        // 1、根据团id出该团相关的订单id
        List<UserOrder> userOrders = adminService.getUserOrders(tourId,tourGenre);
        for(UserOrder uo:userOrders){
            // 2、遍历获取订单id查询该订单出行人
            List<UserOrderDetail> userOrderDetails = adminService.getUserOrderDetails(uo.getUserOrderId());
            // 3、录入t_user_chargeback_detail用户退单详情表
            for(UserOrderDetail uod:userOrderDetails){
                UserChargebackDetail ucd = new UserChargebackDetail();
                ucd.setTravelerId(uod.getTravelerId());
                ucd.setUserChargebackdetailPrice(uod.getUserOrderDetailPrice());
                ucd.setUserOrderId(uod.getUserOrderId());
                ucd.setChargebackRemark("开团失败，无责退款");
                log.info("用户退单详情信息为：{}",ucd);
                int userChargebackDetailId = adminService.addUserChargebackDetail(ucd);
                log.info("用户退单详情信息id：{}",userChargebackDetailId);
                // 获取出行人id，查询出行人信息
                Traveler traveler = adminService.getTraveler(ucd.getTravelerId());
                travelers.add(traveler);
            }
            // 4、用户账户详情表
            UserAccount userAccount = new UserAccount();
            userAccount.setUserId(uo.getUserId());
            userAccount.setUserAccountMoney(uo.getUserOrderPrice());
            userAccount.setUserAccountType("退款");
            userAccount.setUserAccountContent("开团失败，无责退款");
            userAccount.setUserAccountTime(Timestamp.valueOf(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
            int userAccountId = adminService.addUserAccount(userAccount);
            // 5、平台账户详情表
            PlatfromStatement platfromStatement = new PlatfromStatement();
            platfromStatement.setStatementType("开团失败，无责退款");
            platfromStatement.setOrderId(uo.getUserOrderId());
            platfromStatement.setStatementAmount(uo.getUserOrderPrice());
            platfromStatement.setOrderType("用户");
            platfromStatement.setStatementTime(Timestamp.valueOf(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
            int platfromStatementId = adminService.addPlatfromStatement(platfromStatement);
            log.info("自增id为：{}",platfromStatementId);
            // 6、修改平台账户金额
            PlatfromAccount platfromAccount = new PlatfromAccount();
            // 获取账户目前金额（最近的）
            PlatfromAccount pt = adminService.getPlatfromAccount();
            platfromAccount.setPlatfromAccountMoney(pt.getPlatfromAccountMoney()-uo.getUserOrderPrice());
            platfromAccount.setStatementId(platfromStatementId);
            adminService.addPlatfromAccount(platfromAccount);
        }
        // 将出行人信息集合发送到用户服务接收端
        rabbitTemplate.convertAndSend("refund.money.exchange",
                "refund.money.key",
                travelers,
                new CorrelationData("退款信息已发送"));
        //添加一个确认的回调
        rabbitTemplate.setConfirmCallback(callBack);
        log.info("退款操作完成");
        return Result.success("退款成功");
    }

    @Override
    public Result userOrderDetailRefund(int userOrderId, int travelerId, double money, String chargebackRemark) {
        // 修改用户订单详情表状态
        adminService.changeUserOrderDetailStatus(userOrderId,travelerId,chargebackRemark);
        // 查询订单
        UserOrder userOrder = adminService.getUserOrder(userOrderId);
        // 用户账户详情表
        UserAccount userAccount = new UserAccount();
        userAccount.setUserId(userOrder.getUserId());
        userAccount.setUserAccountMoney(money);
        userAccount.setUserAccountType("退款");
        userAccount.setUserAccountContent(chargebackRemark);
        userAccount.setUserAccountTime(Timestamp.valueOf(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
        int userAccountId = adminService.addUserAccount(userAccount);
        // 平台账户详情表
        PlatfromStatement platfromStatement = new PlatfromStatement();
        platfromStatement.setStatementType(chargebackRemark);
        platfromStatement.setOrderId(userOrder.getUserOrderId());
        platfromStatement.setStatementAmount(money);
        platfromStatement.setOrderType("用户");
        platfromStatement.setStatementTime(Timestamp.valueOf(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
        int platfromStatementId = adminService.addPlatfromStatement(platfromStatement);
        log.info("自增id为：{}",platfromStatementId);
        // 修改平台账户金额
        PlatfromAccount platfromAccount = new PlatfromAccount();
        // 获取账户目前金额（最近的）
        PlatfromAccount pt = adminService.getPlatfromAccount();
        platfromAccount.setPlatfromAccountMoney(pt.getPlatfromAccountMoney()-money);
        platfromAccount.setStatementId(platfromStatementId);
        adminService.addPlatfromAccount(platfromAccount);
        // 发送消息
        // 将出行人信息集合发送到用户服务接收端
        Traveler traveler = adminService.getTraveler(travelerId);
        rabbitTemplate.convertAndSend("refund.money.exchange",
                "refund.money.key",
                traveler,
                new CorrelationData("退款信息已发送"));
        //添加一个确认的回调
        rabbitTemplate.setConfirmCallback(callBack);
        log.info("退款操作完成");
        return Result.success("退款成功");
    }

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private CallBack callBack;

    public String sendHotTravel(String hotTravelMessage){
        Map<String,Object> data = new HashMap<>();
        data.put("orderId",new Random().nextLong());
        data.put("hotTravelMessage",hotTravelMessage);
        data.put("orderTime",new Date());
        log.info("发送消息{}",data);
        rabbitTemplate.convertAndSend(
                // 交换机
                RabbitConfig.HOT_TRAVEL_EXCHANGE,
                // 路由键
                RabbitConfig.HOT_TRAVEL_ROUTING_KEY,
                // 发送数据
                data,
                //随消息发送的关联数据
                new CorrelationData(data.get("orderId").toString())
        );
        //添加一个确认的回调
        rabbitTemplate.setConfirmCallback(callBack);
        return "success";
    }

    public String sendCardTimeMessage(){
        List<Card> list=adminService.selectCard();
       List<String> list1=new ArrayList<>();
        for(Card card:list){
            long time = card.getCardIndate().getTime();
            if(time<new Date().getTime()){
                //过期的用户记录下来然后发通知
               list1.add(card.getCardHolder());
            }
        }
        rabbitTemplate.convertSendAndReceive("card.time.exchange","card.time.key",list1,new CorrelationData("请注意！您的身份证信息已经过期,请及时更新您的身份证！"));
        //添加一个确认的回调
        rabbitTemplate.setConfirmCallback(callBack);
        return "success";
    }



}
